/*
    This file is part of Peers, a java SIP softphone.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Copyright 2010 Yohann Martineau 
 */

package net.sourceforge.peers.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;

import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import javax.swing.LayoutStyle.ComponentPlacement;
import com.jd.swing.custom.component.button.* ;
import com.jd.swing.util.Theme;


import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.BorderLayout;


public class MainFrame implements WindowListener, ActionListener {

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(args);
            }
        });
    }

    private static void createAndShowGUI(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        new MainFrame(args);
    }

    private JFrame mainFrame;
    private JPanel mainPanel;
    private JPanel dialerPanel;
    private JTextField uri;
    private JButton actionButton;
    private JLabel statusLabel;

    private EventManager eventManager;
    private Registration registration;
    private Logger logger;
    private JButton hangupButton;
    private JMenuItem menuItem_1;
  

    public MainFrame(final String[] args) {
        String peersHome = Utils.DEFAULT_PEERS_HOME;
        if (args.length > 0) {
            peersHome = args[0];
        }
        logger = new Logger(peersHome);
        String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(lookAndFeelClassName);
        } catch (Exception e) {
            logger.error("cannot change look and feel", e);
        }
        String title = "";
        if (!Utils.DEFAULT_PEERS_HOME.equals(peersHome)) {
            title = peersHome;
        }
        title += "/Peers: SIP User-Agent";
        mainFrame = new JFrame(title);
        mainFrame.setForeground(new Color(138, 43, 226));
        mainFrame.setSize(326, 220);
        mainFrame.setVisible(true);
        int frameWidth = 800;
        int frameHeight = 600;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        mainFrame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.addWindowListener(this);

        mainPanel = new JPanel();
        mainPanel.setBackground(new Color(128, 0, 128));
        mainPanel.setForeground(new Color(139, 0, 139));

        dialerPanel = new JPanel();

        uri = new JTextField("sip:", 15);
        uri.addActionListener(this);

        actionButton = new JButton("Call");
        actionButton.addActionListener(this);

        dialerPanel.add(uri);
        dialerPanel.add(actionButton);
        dialerPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        dialerPanel.setVisible(false);
        statusLabel = new JLabel(title);
        statusLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        Border border = BorderFactory.createEmptyBorder(0, 2, 2, 2);
        statusLabel.setBorder(border);

        Container contentPane = mainFrame.getContentPane();
        contentPane.add(mainPanel, BorderLayout.WEST);

        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menu.setMnemonic('F');
        JMenuItem menuItem = new JMenuItem("Exit");
        menuItem.setMnemonic('x');
        menuItem.setActionCommand(EventManager.ACTION_EXIT);

        registration = new Registration(statusLabel, logger);
        
     final  CircularGlossyButton HelpBtn = new CircularGlossyButton("Click Here",Theme.GLOSSY_BLUE_THEME); 
     HelpBtn.addMouseListener(new MouseAdapter() {
     	@Override
     	public void mouseClicked(MouseEvent e) {
    
     		HelpBtn.setActionCommand(EventManager.ACTION_EXIT);
     	
     	}
     });
        HelpBtn.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		eventManager.windowClosed();
        		//HelpBtn.setActionCommand(EventManager.ACTION_EXIT);
        	}
        });
        HelpBtn.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
        HelpBtn.setTheme(8);
        HelpBtn.setText("Exit");
        
        //GradientButton callButton = new GradientButton("Gradient Button",Theme.GRADIENT_RED_THEME,ButtonType.BUTTON_ROUNDED_RECTANGLUR); 
       JButton callButton = new JButton("");
        callButton.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		eventManager.callClicked("sip:8000@192.168.1.3");
        		
        	}
        });
        callButton.setIcon(new ImageIcon(MainFrame.class.getResource("/net/sourceforge/peers/gui/call3.png")));
        callButton.setToolTipText("\u30B3\u30FC\u30EB\u30DC\u30BF\u30F3\u3092\u62BC\u3059");
       /* try {
            Image img = ImageIO.read(getClass().getResource("calln.png"));
            callButton.setIcon(new ImageIcon(img));
          } catch (IOException ex) {
          }*/
        
       
        //GradientButton hangupButton = new GradientButton("Hang Up",Theme.GRADIENT_BLUE_THEME,ButtonType.BUTTON_ROUNDED); 
        //hangupButton.setSelectedIcon(new ImageIcon(MainFrame.class.getResource("/net/sourceforge/peers/gui/phone.png")));
        hangupButton = new JButton("");
        hangupButton.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent e) {
        		eventManager.hangupClick();
        	}
        });
        hangupButton.setIcon(new ImageIcon(MainFrame.class.getResource("/net/sourceforge/peers/gui/hang3.png")));
        hangupButton.setToolTipText("\u30B3\u30FC\u30EB\u306E\u96FB\u8A71\u3092\u5207\u308B\u306B\u306F\u3001\u30DC\u30BF\u30F3\u3092\u62BC\u3057\u3066\u3001");
        /*try {
            Image img1 = ImageIO.read(getClass().getResource("callhang.jpg"));
            hangupButton.setIcon(new ImageIcon(img1));
          } catch (IOException ex) {
          }*/
        
     final CircularGlossyButton RegisterButton = new CircularGlossyButton("Register", 24);
       
        RegisterButton.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent arg0) {
        		//menuItem.setActionCommand(EventManager.ACTION_PREFERENCES);
               // menuItem.addActionListener(eventManager);
        		 RegisterButton.setActionCommand(EventManager.ACTION_ACCOUNT);
                RegisterButton.addActionListener(eventManager);
        		
        	}
        });
        RegisterButton.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
        RegisterButton.setTheme(5);
        
       final CircularGlossyButton settingsButton = new CircularGlossyButton("Settings", 26);
        settingsButton.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent arg0) {
        		settingsButton.setActionCommand(EventManager.ACTION_ABOUT);
        		settingsButton.addActionListener(eventManager);
        	}
        });
        settingsButton.setText("Help");
        settingsButton.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
        
         final JSlider volumeslider = new JSlider();
       final JLabel volumeLabel = new JLabel("50%");
        volumeslider.addChangeListener(new ChangeListener() {
        	public void stateChanged(ChangeEvent arg0) {
        		volumeLabel.setText(""+volumeslider.getValue()+"%");
        		VolumeControl vl= new VolumeControl();
        		vl.setVolume(volumeslider.getValue());
        		//Audio a= new Audio();
        		//a.setMasterOutputVolume((float)(volumeslider.getValue()/100));
        		/*try{
        			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
        				    new File("D:/ti-world.wav"));
        		Clip clip = AudioSystem.getClip();
        		clip.open(audioInputStream);
        		FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        			gainControl.setValue(volumeslider.getValue());
        		}
        		catch(Exception e){
        			JOptionPane.showMessageDialog(volumeLabel, e);
        		}*/
        	}
        });
        volumeslider.setBackground(new Color(255, 105, 180));
        
        JLabel lblVolume = new JLabel("Volume");
        
      
        
        GroupLayout gl_mainPanel = new GroupLayout(mainPanel);
        gl_mainPanel.setHorizontalGroup(
        	gl_mainPanel.createParallelGroup(Alignment.LEADING)
        		.addGroup(gl_mainPanel.createSequentialGroup()
        			.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
        				.addGroup(gl_mainPanel.createSequentialGroup()
        					.addContainerGap()
        					.addComponent(lblVolume)
        					.addPreferredGap(ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
        					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
        						.addComponent(RegisterButton, GroupLayout.PREFERRED_SIZE, 153, GroupLayout.PREFERRED_SIZE)
        						.addComponent(volumeslider, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        					.addPreferredGap(ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
        					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
        						.addGroup(gl_mainPanel.createSequentialGroup()
        							.addComponent(settingsButton, GroupLayout.PREFERRED_SIZE, 161, GroupLayout.PREFERRED_SIZE)
        							.addGap(111)
        							.addComponent(HelpBtn, GroupLayout.PREFERRED_SIZE, 157, GroupLayout.PREFERRED_SIZE))
        						.addGroup(gl_mainPanel.createSequentialGroup()
        							.addGap(18)
        							.addComponent(volumeLabel))))
        				.addComponent(dialerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addGroup(gl_mainPanel.createSequentialGroup()
        					.addContainerGap()
        					.addComponent(statusLabel))
        				.addGroup(Alignment.TRAILING, gl_mainPanel.createSequentialGroup()
        					.addContainerGap()
        					.addComponent(callButton, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
        					.addGap(137)
        					.addComponent(hangupButton, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
        					.addGap(163)))
        			.addGap(80))
        );
        gl_mainPanel.setVerticalGroup(
        	gl_mainPanel.createParallelGroup(Alignment.LEADING)
        		.addGroup(gl_mainPanel.createSequentialGroup()
        			.addComponent(dialerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        			.addGap(6)
        			.addComponent(statusLabel)
        			.addGap(56)
        			.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
        				.addComponent(RegisterButton, GroupLayout.PREFERRED_SIZE, 139, GroupLayout.PREFERRED_SIZE)
        				.addComponent(settingsButton, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
        				.addComponent(HelpBtn, GroupLayout.PREFERRED_SIZE, 135, GroupLayout.PREFERRED_SIZE))
        			.addGap(43)
        			.addGroup(gl_mainPanel.createParallelGroup(Alignment.TRAILING)
        				.addComponent(callButton, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)
        				.addComponent(hangupButton, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE))
        			.addPreferredGap(ComponentPlacement.RELATED, 131, Short.MAX_VALUE)
        			.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
        				.addComponent(volumeslider, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(volumeLabel, Alignment.TRAILING)
        				.addComponent(lblVolume, Alignment.TRAILING))
        			.addGap(40))
        );
        mainPanel.setPreferredSize(new Dimension(800,600));
        mainPanel.setLayout(gl_mainPanel);

        Thread thread = new Thread(new Runnable() {
            public void run() {
                String peersHome = Utils.DEFAULT_PEERS_HOME;
               
                if (args.length > 0) {
                    peersHome = args[0];
                }
                eventManager = new EventManager(MainFrame.this,
                        peersHome, logger);
                try {
                    eventManager.register();
                } catch (SipUriSyntaxException e) {
                    statusLabel.setText(e.getMessage());
                }
            }
        });
        thread.start();

        try {
            while (eventManager == null) {
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            return;
        }
        menuItem.addActionListener(eventManager);
        menu.add(menuItem);
        menuBar.add(menu);

        menu = new JMenu("Edit");
        menu.setMnemonic('E');
        menuItem_1 = new JMenuItem("Account");
        menuItem_1.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent arg0) {
        	}
        });
        menuItem_1.setMnemonic('A');
        menuItem_1.addActionListener(eventManager);
        menu.add(menuItem_1);
        menuItem = new JMenuItem("Preferences");
        menuItem.setMnemonic('P');
        menuItem.setActionCommand(EventManager.ACTION_PREFERENCES);
        menuItem.addActionListener(eventManager);
        menu.add(menuItem);
        menuBar.add(menu);

        menu = new JMenu("Help");
        menu.setMnemonic('H');
        menuItem = new JMenuItem("User manual");
        menuItem.setMnemonic('D');
        menuItem.setActionCommand(EventManager.ACTION_DOCUMENTATION);
        menuItem.addActionListener(eventManager);
        menu.add(menuItem);
        menuItem = new JMenuItem("About");
        menuItem.setMnemonic('A');
        menuItem.setActionCommand(EventManager.ACTION_ABOUT);
        menuItem.addActionListener(eventManager);
       // menu.add(menuItem);
       // menuBar.add(menu);

       // mainFrame.setJMenuBar(menuBar);

        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    // window events

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowClosed(WindowEvent e) {
        eventManager.windowClosed();
    }

    @Override
    public void windowClosing(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }

    // action event

    @Override
    public void actionPerformed(ActionEvent e) {
        eventManager.callClicked(uri.getText());
    }

    // misc.
    public void setLabelText(String text) {
        statusLabel.setText(text);
        mainFrame.pack();
    }

    public void registerFailed(SipResponse sipResponse) {
        registration.registerFailed();
    }

    public void registerSuccessful(SipResponse sipResponse) {
        registration.registerSuccessful();
    }

    public void registering(SipRequest sipRequest) {
        registration.registerSent();
    }

    public void socketExceptionOnStartup() {
        JOptionPane.showMessageDialog(mainFrame, "peers SIP port " +
        		"unavailable, exiting");
        System.exit(1);
    }
}
